//
//  ComplainCommentsController.m
//  protesteya
//
//  Created by Sebastian Bene on 9/29/13.
//  Copyright (c) 2013 Obligatorio Dispositivos Moviles. All rights reserved.
//

#import "ComplainCommentsController.h"

@interface ComplainCommentsController ()

@property (strong, nonatomic) TwitterInvoker *invoker;
@property GetTweetsListResponse *response;
@property (weak, nonatomic) IBOutlet UITextField *comment;
@property NSMutableArray *tweetsList;
@property NSMutableDictionary *userImages;

-(void) ProcessTweetList;
-(Comment*) CreateComment:(NSDictionary *)tweet;

@end

@implementation ComplainCommentsController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    
    NSString* boldFontName = @"Avenir-Black";
    
    [self styleNavigationBarWithFontName:boldFontName];
    
    self.commentsTableView.dataSource = self;
    self.commentsTableView.delegate = self;
    
    self.commentsTableView.backgroundColor = [UIColor whiteColor];
    self.commentsTableView.separatorColor = [UIColor colorWithWhite:0.9 alpha:0.6];
    
    self.comment.delegate = self;
    
    _invoker = [[TwitterInvoker alloc] init];
    _invoker.tweeterInvokerDelegate = self;
    
    self.tweetsList = [[NSMutableArray alloc] init];
    self.userImages = [[NSMutableDictionary alloc] init];
    GetTweetCommentsRequest *request = [[GetTweetCommentsRequest alloc] init];
    
    NSDictionary *user = self.tweet[@"user"];
    request.user = user[@"screen_name"];
    
    [_invoker GetTweetComments:request];
}

- (void)viewWillAppear:(BOOL)animated
{
    // register for keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    // unregister for keyboard notifications while not visible.
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
}

#define kOFFSET_FOR_KEYBOARD 170.0

-(void)keyboardWillShow {
    // Animate the current view out of the way
    if (self.view.frame.origin.y >= 0)
    {
        [self setViewMovedUp:YES];
    }
    else if (self.view.frame.origin.y < 0)
    {
        [self setViewMovedUp:NO];
    }
}

-(void)keyboardWillHide {
    if (self.view.frame.origin.y >= 0)
    {
        [self setViewMovedUp:YES];
    }
    else if (self.view.frame.origin.y < 0)
    {
        [self setViewMovedUp:NO];
    }
}

//method to move the view up/down whenever the keyboard is shown/dismissed
-(void)setViewMovedUp:(BOOL)movedUp
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3]; // if you want to slide up the view
    
    CGRect rect = self.view.frame;
    if (movedUp)
    {
        // 1. move the view's origin up so that the text field that will be hidden come above the keyboard
        // 2. increase the size of the view so that the area behind the keyboard is covered up.
        rect.origin.y -= kOFFSET_FOR_KEYBOARD;
        rect.size.height += kOFFSET_FOR_KEYBOARD;
    }
    else
    {
        // revert back to the normal state.
        rect.origin.y += kOFFSET_FOR_KEYBOARD;
        rect.size.height -= kOFFSET_FOR_KEYBOARD;
    }
    self.view.frame = rect;
    
    [UIView commitAnimations];
}

- (NSString *)searchMessageForState:(TwitterSearchState)state
{
    switch (state)
    {
        case TwitterSearchStateLoading:
            return @"Cargando...";
            break;
        case TwitterSearchStateNotFound:
            return @"No se encontraron resultados";
            break;
        case TwitterSearchStateRefused:
            return @"Acceso a Twitter denegado";
            break;
        default:
            return @"No Disponible";
            break;
    }
}

-(void) setDetail:(NSDictionary *) tweet
{
    self.tweet = tweet;
}

-(void)getResponse:(NSDictionary *)response
{
    ResponseParser *parser = [[ResponseParser alloc] init];
    TwitterBaseResponse* baseResponse = [parser ParseCommentsListResponse:(NSDictionary *)response inReplyTo:(NSString *) self.tweet[@"id_str"]];
    
    if ([baseResponse isKindOfClass:[GetTweetsListResponse class]]) {
        self.response = (GetTweetsListResponse *)baseResponse;
        
        if(self.response.responseType == TwitterResponseError)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:self.response.errorMessage delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
        }
        else
        {
            [self ProcessTweetList];
            [self.commentsTableView reloadData];
            [self.commentsTableView flashScrollIndicators];
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        }
    
        _invoker.tweeterInvokerDelegate = nil;
    }else{
        Comment* comment = [self CreateComment:((GetTweetResponse *)baseResponse).tweet];
        [self.tweetsList insertObject:comment atIndex:0];
        [self.commentsTableView reloadData];
        [self.commentsTableView flashScrollIndicators];
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        [DejalBezelActivityView removeViewAnimated:YES];

    }
}

-(Comment*) CreateComment:(NSDictionary *)tweet {
    
    NSDictionary* user = tweet[@"user"];
    
    Comment* comment = [[Comment alloc] init];
    
    comment.user = user[@"name"];
    
    NSDictionary* complainOWner = self.tweet[@"user"];
    NSString* complainOwnerName = [[@"@" stringByAppendingString:complainOWner[@"screen_name"]] stringByAppendingString:@" "];
    NSString *tweetText = [tweet[@"text"] stringByReplacingOccurrencesOfString:HASHTAG withString:@""];
    tweetText = [tweetText stringByReplacingOccurrencesOfString:complainOwnerName withString:@""];
    NSDataDetector *detect = [[NSDataDetector alloc] initWithTypes:NSTextCheckingTypeLink error:nil];
    NSArray *matches = [detect matchesInString:tweetText options:0 range:NSMakeRange(0, [tweetText length])];
    for (NSTextCheckingResult *match in matches) {
        
        NSURL *url = [match URL];
        NSString *urlDescription = [url description];
        tweetText = [tweetText stringByReplacingOccurrencesOfString:urlDescription withString:@""];
    }
    comment.text = tweetText;
    
    comment.date = [tweet[@"created_at"] substringToIndex:16];
    
    UIImage* userImage = self.userImages[user[@"profile_image_url"]];
    if (userImage) {
        comment.image = userImage;
    }
    else
    {
        NSURL *url = [NSURL URLWithString: user[@"profile_image_url"]];
        NSData *data = [[NSData alloc] initWithContentsOfURL:url];
        UIImage *tmpImage = [[UIImage alloc] initWithData:data];
        self.userImages[user[@"profile_image_url"]] = tmpImage;
        comment.image = tmpImage;
    }
    return comment;
}

-(void) ProcessTweetList{
    for (NSDictionary* tweet in self.response.tweetsList) {
        
        Comment* comment = [self CreateComment:tweet];
        [self.tweetsList addObject:comment];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSUInteger count = [self.tweetsList count];
    return count > 0 ? count : 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ResultCellIdentifier = @"ResultCell";
    static NSString *LoadCellIdentifier = @"LoadingCell";
    
    NSUInteger count = [self.tweetsList count];
    if ((count == 0) && (indexPath.row == 0))
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LoadCellIdentifier];
        cell.textLabel.text = [self searchMessageForState:self.response.searchState];
        return cell;
    }

    Comment *comment = (self.tweetsList)[indexPath.row];
    CommentCell *cell = [tableView dequeueReusableCellWithIdentifier:ResultCellIdentifier];
    
    cell.nameLabel.text = comment.user;
    cell.commentLabel.text = comment.text;
    cell.dateLabel.text = comment.date;
    cell.profileImageView.image = comment.image;

    return cell;
}

- (IBAction)sendComment:(id)sender {
    [DejalBezelActivityView activityViewForView:self.view withLabel:@"Enviando Comentario..."];
    
    _invoker = [[TwitterInvoker alloc] init];
    _invoker.tweeterInvokerDelegate = self;
    
    SendTweetRequest *request = [[SendTweetRequest alloc] init];
    
    NSDictionary* user = self.tweet[@"user"];
    NSString* userName = [[@"@" stringByAppendingString:user[@"screen_name"]] stringByAppendingString:@" "];
    request.text = [userName stringByAppendingString:self.comment.text];
    request.inReplyToStatusId = self.tweet[@"id_str"];
    
    [_invoker SendTweet:request];
    
    self.comment.text = @"";
    [self.comment resignFirstResponder];

}

-(void)styleNavigationBarWithFontName:(NSString*)navigationTitleFont{
    
    
    CGSize size = CGSizeMake(320, 44);
    UIColor* color = [UIColor whiteColor];
    
    UIGraphicsBeginImageContext(size);
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    CGRect fillRect = CGRectMake(0,0,size.width,size.height);
    CGContextSetFillColorWithColor(currentContext, color.CGColor);
    CGContextFillRect(currentContext, fillRect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    
    UINavigationBar* navAppearance = [UINavigationBar appearance];
    
    [navAppearance setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    
    [navAppearance setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                           [UIColor colorWithRed:28.0/255 green:158.0/255 blue:121.0/255 alpha:1.0f], UITextAttributeTextColor,
                                           [UIFont fontWithName:navigationTitleFont size:18.0f], UITextAttributeFont, [NSValue valueWithCGSize:CGSizeMake(0.0, 0.0)], UITextAttributeTextShadowOffset,
                                           nil]];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    NSIndexPath *indexPath = [self.commentsTableView indexPathForSelectedRow];
    if(indexPath)
    {
        NSDictionary *tweet = [_response.tweetsList objectAtIndex:indexPath.row];
        [segue.destinationViewController setDetail:tweet];
    }
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return (newLength > 100) ? NO : YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self sendComment:nil];
    return YES;
}

@end
